<?php
// 修复路径问题 - 使用绝对路径
$adminDir = __DIR__;
$projectRoot = dirname($adminDir);

require_once $projectRoot . '/config/config.php';
require_once $projectRoot . '/includes/auth.php';
require_once $projectRoot . '/includes/database.php';

// 检查登录状态
requireLogin();

// 初始化数据库
$db = new Database();

// 获取系统设置（包含动态标题）
$settings = $db->getSettings();
$siteTitle = $settings['site_title'] ?? SITE_TITLE;

// 获取统计数据
$stats = $db->getStats();
$categories = $db->getCategories();
$navigations = $db->getNavigations();

// 计算今日访问量
$today = date('Y-m-d');
$todayVisits = $stats['daily_visits'][$today] ?? 0;

// 计算今日搜索量
$todaySearches = $stats['daily_searches'][$today] ?? 0;
$totalSearches = $stats['total_search_count'] ?? ($stats['search_count'] ?? 0); // 兼容旧版

// 获取热门链接
$popularLinks = array_filter($navigations, function($nav) {
    return isset($nav['clicks']) && $nav['clicks'] > 0;
});
usort($popularLinks, function($a, $b) {
    return ($b['clicks'] ?? 0) - ($a['clicks'] ?? 0);
});
$popularLinks = array_slice($popularLinks, 0, 10);

// 获取最新搜索关键词
$recentKeywords = $db->getRecentKeywords(20);

// 处理退出登录
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    doLogout();
    header('Location: ' . getPageUrl('admin_login'));
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - <?php echo $siteTitle; ?></title>
    
    <!-- 样式文件 -->
    <link rel="stylesheet" href="<?php echo asset('css/admin.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/fontawesome/all.min.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/chartjs/chart.min.css'); ?>">
    
    <!-- JavaScript配置文件 - 必须在其他JS文件之前加载 -->
    <script src="<?php echo asset('js/config.js'); ?>"></script>
    
    <!-- 网站图标 -->
    <link rel="icon" type="image/x-icon" href="<?php echo asset('images/favicon.ico'); ?>">
</head>
<body class="admin-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <i class="fas fa-compass"></i>
                <h2><?php echo $siteTitle; ?></h2>
            </div>
        </div>
        
        <nav class="sidebar-nav">
            <ul>
                <li class="active">
                    <a href="<?php echo getUrl('admin/dashboard'); ?>">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表盘</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/navigations'); ?>">
                        <i class="fas fa-link"></i>
                        <span>导航管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/categories'); ?>">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/settings'); ?>">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl(); ?>" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                        <span>访问前台</span>
                    </a>
                </li>
            </ul>
        </nav>
        
        <div class="sidebar-footer">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span><?php echo $_SESSION['admin_username'] ?? 'Admin'; ?></span>
            </div>
            <a href="<?php echo getUrl('admin/index.php?action=logout'); ?>" class="logout-btn" title="退出登录">
                <i class="fas fa-sign-out-alt"></i>
            </a>
        </div>
    </aside>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
        <!-- 顶部栏 -->
        <header class="content-header">
            <div class="header-left">
                <h1><i class="fas fa-tachometer-alt"></i> 仪表盘</h1>
                <p>欢迎回来，管理员！这里是您的导航系统控制台。</p>
            </div>
            <div class="header-right">
                <div class="datetime">
                    <div class="time" id="currentTime"></div>
                    <div class="date" id="currentDate"></div>
                </div>
            </div>
        </header>
        
        <!-- 统计卡片 -->
        <section class="stats-cards">
            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-calendar-day text-success"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo number_format($todayVisits); ?></h3>
                    <p>今日访问</p>
                </div>
            </div>

            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-eye text-primary"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo number_format($stats['total_visits'] ?? 0); ?></h3>
                    <p>总访问量</p>
                </div>
            </div>
            
            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-search-plus text-success"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo number_format($todaySearches); ?></h3>
                    <p>今日搜索</p>
                </div>
            </div>

            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-search text-warning"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo number_format($totalSearches); ?></h3>
                    <p>总搜索次数</p>
                </div>
            </div>
            
            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-folder text-info"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo count($categories); ?></h3>
                    <p>分类数量</p>
                </div>
            </div>
            
            <div class="card">
                <div class="card-icon">
                    <i class="fas fa-link text-secondary"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo count($navigations); ?></h3>
                    <p>导航数量</p>
                </div>
            </div>
        </section>
        
        <!-- 图表和列表 -->
        <section class="dashboard-content">
            <!-- 访问量趋势图 - 独占一行 -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card chart-card">
                        <div class="card-header">
                            <h3><i class="fas fa-chart-line"></i> 访问量趋势</h3>
                            <p>最近30天的访问量变化</p>
                        </div>
                        <div class="card-body">
                            <canvas id="visitsChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 热门链接和最新搜索 - 并排展示 -->
            <div class="row">
                <!-- 热门链接 -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-fire"></i> 热门链接</h3>
                            <p>点击次数最多的导航</p>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($popularLinks)): ?>
                                <div class="popular-links">
                                    <?php foreach ($popularLinks as $index => $link): ?>
                                        <div class="popular-item">
                                            <div class="rank"><?php echo $index + 1; ?></div>
                                            <div class="info">
                                                <div class="name">
                                                    <a href="<?php echo htmlspecialchars($link['url']); ?>" target="_blank" class="link-title">
                                                        <?php echo htmlspecialchars($link['name']); ?>
                                                    </a>
                                                </div>
                                                <div class="clicks"><?php echo $link['clicks']; ?> 次点击</div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-chart-bar"></i>
                                    <p>暂无点击数据</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- 最新搜索关键词 -->
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-search"></i> 最新搜索</h3>
                            <p>最近搜索的关键词</p>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($recentKeywords)): ?>
                                <div class="search-keywords">
                                    <?php foreach ($recentKeywords as $index => $keyword): ?>
                                        <div class="keyword-item">
                                            <div class="keyword-info">
                                                <div class="keyword-text">
                                                    <?php
                                                        // 根据存储的搜索引擎信息生成正确的搜索链接
                                                        $engine = isset($keyword['engine']) ? $keyword['engine'] : 'baidu';
                                                        $searchUrl = '';
                                                        
                                                        switch($engine) {
                                                            case 'baidu':
                                                                $searchUrl = 'https://www.baidu.com/s?wd=' . urlencode($keyword['keyword']);
                                                                break;
                                                            case 'bing':
                                                                $searchUrl = 'https://www.bing.com/search?q=' . urlencode($keyword['keyword']);
                                                                break;
                                                            default:
                                                                $searchUrl = 'https://www.baidu.com/s?wd=' . urlencode($keyword['keyword']);
                                                        }
                                                    ?>
                                                    <a href="<?php echo $searchUrl; ?>" target="_blank" class="link-title">
                                                        <i class="fas fa-search"></i>
                                                        <?php echo htmlspecialchars($keyword['keyword']); ?>
                                                    </a>
                                                </div>
                                                <div class="keyword-meta">
                                                    <span class="search-count"><?php echo $keyword['count']; ?> 次</span>
                                                    <span class="last-time" title="最后搜索时间: <?php echo $keyword['last_searched']; ?>">
                                                        <?php 
                                                        $lastTime = strtotime($keyword['last_searched']);
                                                        $timeAgo = time() - $lastTime;
                                                         
                                                        if ($timeAgo < 60) {
                                                            echo '刚刚';
                                                        } elseif ($timeAgo < 3600) {
                                                            echo floor($timeAgo / 60) . '分钟前';
                                                        } elseif ($timeAgo < 86400) {
                                                            echo floor($timeAgo / 3600) . '小时前';
                                                        } elseif ($timeAgo < 2592000) {
                                                            echo floor($timeAgo / 86400) . '天前';
                                                        } else {
                                                            echo date('m-d', $lastTime);
                                                        }
                                                        ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="empty-state">
                                    <i class="fas fa-search"></i>
                                    <p>暂无搜索记录</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 分类概览 -->
            <div class="content-section">
                <div class="section-header">
                    <h2><i class="fas fa-th-large"></i> 分类概览</h2>
                </div>
                
                <div class="categories-overview">
                    <?php
                    // 按排序序号升序排列分类
                    usort($categories, function($a, $b) {
                        return ($a['sort'] ?? 0) - ($b['sort'] ?? 0);
                    });
                    ?>
                    <?php foreach ($categories as $category): ?>
                        <?php 
                        $categoryNavs = $db->getNavigations($category['id']);
                        $totalClicks = array_sum(array_column($categoryNavs, 'clicks'));
                        ?>
                        <div class="category-item">
                            <div class="category-icon">
                                <i class="<?php echo htmlspecialchars($category['icon']); ?>"></i>
                            </div>
                            <div class="category-info">
                                <h4><?php echo htmlspecialchars($category['name']); ?></h4>
                                <p><i class="fas fa-link"></i> <?php echo count($categoryNavs); ?> 个导航</p>
                                <p><i class="fas fa-mouse-pointer"></i> <?php echo number_format($totalClicks); ?> 次点击</p>
                            </div>
                            <div class="category-actions">
                                <a href="<?php echo getPageUrl('admin_categories', ['id' => $category['id']]); ?>" 
                                   class="btn btn-primary btn-sm">
                                    <i class="fas fa-cog"></i> 管理
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
    </main>
    
    <!-- JavaScript -->
            <script src="<?php echo asset('libs/chartjs/chart.min.js'); ?>"></script>
    <script>
        // 扩展配置信息 - API URL已经在config.js中设置为不带.php后缀
        Object.assign(window.CONFIG, {
            baseUrl: '<?php echo BASE_URL; ?>',
            siteUrl: '<?php echo SITE_URL; ?>',
            assetsUrl: '<?php echo asset(""); ?>'
        });
        
        // 统计数据
        window.STATS_DATA = {
            dailyVisits: <?php echo json_encode($stats['daily_visits'] ?? [], JSON_UNESCAPED_UNICODE); ?>,
            popularLinks: <?php echo json_encode($popularLinks, JSON_UNESCAPED_UNICODE); ?>
        };
        
        // 记录配置已加载
        window.CONFIG.log('info', '管理后台已加载，配置完成');
    </script>
    <script src="<?php echo asset('js/admin.js'); ?>"></script>
</body>
</html>